#include "PVS_Engine.h"
#include "Eveluation.h"
#include "SearchEngine.h"
#include "MoveGenerator.h"
#include <string.h>

CHESSMOVE m_cmBestMovePVS;

void SearchAGoodMovePVS(int position[10][9])
{
	memcpy(CurPosition, position, 360);
	m_nMaxDepth = m_nSearchDepth;
	initEveluate();

//	for (m_nMaxDepth = 1; m_nMaxDepth <= m_nSearchDepth; m_nMaxDepth++)
	{
	   PrincipalVariation(m_nMaxDepth, -20000, 20000);
	}
	moves[0] = m_cmBestMovePVS.From.x;
	moves[1] = m_cmBestMovePVS.From.y;
	moves[2] = m_cmBestMovePVS.To.x;
	moves[3] = m_cmBestMovePVS.To.y;
	MakeMove(&m_cmBestMovePVS);
	memcpy(position, CurPosition, 360);
}

int PrincipalVariation(int depth, int alpha, int beta)
{
	int score;
	int Count,i;
	int type;
	int best;

	i = IsGameOver(CurPosition, depth);
	if (i != 0)
		return i;

	if (depth <= 0)	//?????????
		return Eveluate(CurPosition, (m_nMaxDepth-depth)%2==1);
	
	Count = CreatePossibleMove(CurPosition, depth, (m_nMaxDepth-depth)%2);
	

	type = MakeMove(&m_MoveList[depth][0]);
	best = -PrincipalVariation( depth-1, -beta, -alpha);
	UnMakeMove(&m_MoveList[depth][0],type); 
	
	if(depth == m_nMaxDepth)
	{
		if(is_rule==true)
		{
			if(m_MoveList[depth][0].From.x!=moves[1]||m_MoveList[depth][0].From.y!=moves[0]||m_MoveList[depth][0].To.x!=moves[3]||m_MoveList[depth][0].To.y!=moves[2])
			{
				m_cmBestMovePVS = m_MoveList[depth][0];
			}
		}
		else
		{
			m_cmBestMovePVS = m_MoveList[depth][0];
		}
	}

	for (i=1;i<Count;i++) 
	{
		
		if(best < beta) 
		{
			if (best > alpha) 
				alpha = best;
			type = MakeMove(&m_MoveList[depth][i]);
			score = -PrincipalVariation(depth-1, -alpha-1, -alpha);
			if (score > alpha && score < beta) 
			{
				best = -PrincipalVariation(depth-1, -beta, -score);
				if(depth == m_nMaxDepth)
				{
					if(is_rule==true)
					{
						if(m_MoveList[depth][i].From.x!=moves[1]||m_MoveList[depth][i].From.y!=moves[0]||m_MoveList[depth][i].To.x!=moves[3]||m_MoveList[depth][i].To.y!=moves[2])
						{
							m_cmBestMovePVS = m_MoveList[depth][i];
						}
					}
					else
					{
						m_cmBestMovePVS = m_MoveList[depth][i];
					}
				}
			}
			else if (score > best)
			{
				best = score;
				if(depth == m_nMaxDepth)
				{
					if(is_rule==true)
					{
						if(m_MoveList[depth][i].From.x!=moves[1]||m_MoveList[depth][i].From.y!=moves[0]||m_MoveList[depth][i].To.x!=moves[3]||m_MoveList[depth][i].To.y!=moves[2])
						{
							m_cmBestMovePVS = m_MoveList[depth][i];
						}
					}
					else
					{
						m_cmBestMovePVS = m_MoveList[depth][i];
					}
				}
			}
			UnMakeMove(&m_MoveList[depth][i],type); 
		}
	}

	return best;
}